// 获取店铺申请数据
let shopApplicationData = {};

// 使用异步方式获取数据
$(document).ready(function() {
    $.ajax({
        url: '/shop/getShopsByAduit',
        type: "GET",
        data: {
            id: $.cookie("userOwnerId")
        },
        success: function(response) {
            if (response.code === 200 && response.data) {
                shopApplicationData = response.data;
                renderShopApplication(shopApplicationData);
            } else {
                console.error('获取数据失败:', response.message);
                showErrorMessage('获取店铺申请数据失败');
            }
        },
        error: function(xhr, status, error) {
            console.error('请求失败:', error);
            showErrorMessage('网络请求失败，请稍后重试');
        }
    });
});

// 渲染店铺申请数据
function renderShopApplication(data) {
    if (!data) {
        showErrorMessage('数据为空');
        return;
    }

    // 设置基本信息
    document.getElementById('shopAvatar').src = data.avatarUrl || getDefaultAvatar();
    document.getElementById('shopName').textContent = data.shopName || '未填写';
    document.getElementById('shopDesc').textContent = data.shopDesc || '未填写';

    // 营业时间
    const businessHours = data.openTime && data.closeTime ?
        `${formatTime(data.openTime)} - ${formatTime(data.closeTime)}` : '未设置';
    document.getElementById('businessHours').textContent = businessHours;

    // 地理位置
    const location = data.longitude && data.latitude ?
        `经度: ${data.longitude}, 纬度: ${data.latitude}` : '未设置';
    document.getElementById('location').textContent = location;

    // 申请时间
    document.getElementById('createdTime').textContent = formatDateTime(data.createdTime);

    // 设置状态徽章
    setStatusBadge(data.status);

    // 渲染店铺图片
    renderShopImages(data.bannerUrls);

    // 渲染资质证明文件 - 处理JSON字符串格式
    renderDocumentsFromJson(data.businessLicense, 'businessLicenseDocs', '营业执照');
    renderDocumentsFromJson(data.verifyImg, 'verifyDocs', '验证材料');

    // 设置审核信息
    document.getElementById('auditPerson').textContent = data.aduitPerson || '待审核';
    document.getElementById('auditTime').textContent = data.aduitTime ? formatDateTime(data.aduitTime) : '待审核';
    document.getElementById('auditDesc').textContent = data.aduitDesc || '暂无说明';
}

// 从JSON字符串渲染文档文件
function renderDocumentsFromJson(documentsJson, containerId, defaultTitle) {
    const container = document.getElementById(containerId);

    if (!documentsJson) {
        container.innerHTML = `<div class="info-value empty">暂无${defaultTitle}</div>`;
        return;
    }

    try {
        // 解析JSON字符串
        const urls = JSON.parse(documentsJson);
        if (!urls || urls.length === 0) {
            container.innerHTML = `<div class="info-value empty">暂无${defaultTitle}</div>`;
            return;
        }

        container.innerHTML = '';
        urls.forEach((url, index) => {
            // 从URL中提取文件名
            const fileName = getFileNameFromUrl(url) || `${defaultTitle}_${index + 1}`;
            const fileExt = getFileExtension(fileName);

            const documentItem = document.createElement('div');
            documentItem.className = 'document-item';

            let previewContent = '';
            let fileType = 'image';

            if (isImageFile(fileExt)) {
                previewContent = `
                    <div class="document-preview" onclick="previewFile('${url}', '${fileName}', 'image')">
                        <img src="${url}" alt="${fileName}" style="width: 100%; height: 100%; object-fit: cover;">
                    </div>
                `;
            } else if (isPdfFile(fileExt)) {
                previewContent = `
                    <div class="document-preview">
                        <i class="bi bi-file-earmark-pdf file-icon pdf-icon"></i>
                    </div>
                `;
                fileType = 'pdf';
            } else if (isWordFile(fileExt)) {
                previewContent = `
                    <div class="document-preview">
                        <i class="bi bi-file-earmark-word file-icon word-icon"></i>
                    </div>
                `;
                fileType = 'word';
            } else {
                previewContent = `
                    <div class="document-preview">
                        <i class="bi bi-file-earmark file-icon"></i>
                    </div>
                `;
                fileType = 'other';
            }

            documentItem.innerHTML = `
                ${previewContent}
                <div class="info-label" title="${fileName}">${truncateFileName(fileName)}</div>
                <div class="document-actions">
                    <button class="document-btn preview" onclick="previewFile('${url}', '${fileName}', '${fileType}')">
                        <i class="bi bi-eye"></i> 预览
                    </button>
                    <button class="document-btn download" onclick="downloadFile('${url}', '${fileName}')">
                        <i class="bi bi-download"></i> 下载
                    </button>
                </div>
            `;

            container.appendChild(documentItem);
        });
    } catch (e) {
        console.error('解析文档数据失败:', e);
        container.innerHTML = `<div class="info-value empty">${defaultTitle}数据格式错误</div>`;
    }
}

// 从URL中提取文件名
function getFileNameFromUrl(url) {
    if (!url) return '';
    try {
        const urlObj = new URL(url);
        const pathname = urlObj.pathname;
        return pathname.substring(pathname.lastIndexOf('/') + 1);
    } catch (e) {
        // 如果不是完整URL，尝试直接处理
        return url.substring(url.lastIndexOf('/') + 1);
    }
}

// 截断过长的文件名
function truncateFileName(fileName, maxLength = 20) {
    if (!fileName) return '未知文件';
    if (fileName.length <= maxLength) return fileName;
    const extension = getFileExtension(fileName);
    const nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
    const truncatedName = nameWithoutExt.substring(0, maxLength - 3 - extension.length);
    return `${truncatedName}...${extension}`;
}

// 文件类型判断函数
function isImageFile(ext) {
    return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext.toLowerCase());
}

function isPdfFile(ext) {
    return ext.toLowerCase() === 'pdf';
}

function isWordFile(ext) {
    return ['doc', 'docx'].includes(ext.toLowerCase());
}

// 预览文件
function previewFile(url, fileName, fileType) {
    const modal = document.getElementById('fileModal');
    const modalTitle = document.getElementById('fileModalTitle');
    const modalBody = document.getElementById('fileModalBody');

    modalTitle.textContent = `预览: ${fileName}`;
    modalBody.innerHTML = '';

    if (fileType === 'image') {
        // 图片预览
        modalBody.innerHTML = `<img src="${url}" alt="${fileName}" class="image-viewer">`;
    } else if (fileType === 'pdf') {
        // PDF预览（使用Google Docs Viewer）
        modalBody.innerHTML = `
            <iframe src="https://docs.google.com/gview?url=${encodeURIComponent(url)}&embedded=true" 
                    class="pdf-viewer" frameborder="0"></iframe>
        `;
    } else if (fileType === 'word') {
        // Word文档预览（使用Google Docs Viewer）
        modalBody.innerHTML = `
            <iframe src="https://docs.google.com/gview?url=${encodeURIComponent(url)}&embedded=true" 
                    class="doc-viewer" frameborder="0"></iframe>
        `;
    } else {
        // 其他文件类型显示下载提示
        modalBody.innerHTML = `
            <div style="text-align: center; padding: 40px;">
                <i class="bi bi-file-earmark" style="font-size: 64px; color: #6c757d; margin-bottom: 20px;"></i>
                <h3>不支持在线预览</h3>
                <p>此文件类型不支持在线预览，请下载后查看</p>
                <button class="btn btn-primary" onclick="downloadFile('${url}', '${fileName}')" style="margin-top: 20px;">
                    <i class="bi bi-download"></i> 下载文件
                </button>
            </div>
        `;
    }

    modal.style.display = 'flex';
}

// 关闭文件预览模态框
function closeFileModal() {
    document.getElementById('fileModal').style.display = 'none';
}

// 下载文件
function downloadFile(url, fileName) {
    // 创建临时下载链接
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 获取文件扩展名
function getFileExtension(filename) {
    if (!filename) return '';
    return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2).toLowerCase();
}

// 设置状态徽章
function setStatusBadge(status) {
    const badge = document.getElementById('statusBadge');

    switch(status) {
        case 0: // 待审核
            badge.className = 'status-badge status-pending';
            badge.textContent = '待审核';
            break;
        case 1: // 审核通过
            badge.className = 'status-badge status-approved';
            badge.textContent = '审核通过';
            break;
        case 2: // 审核不通过
            badge.className = 'status-badge status-rejected';
            badge.textContent = '审核不通过';
            break;
        default:
            badge.className = 'status-badge status-pending';
            badge.textContent = '未知状态';
    }
}

// 渲染店铺图片
function renderShopImages(bannerUrls) {
    const imagesContainer = document.getElementById('shopImages');

    if (!bannerUrls) {
        imagesContainer.innerHTML = '<div class="info-value empty">暂无图片</div>';
        return;
    }

    try {
        const urls = JSON.parse(bannerUrls);
        if (urls.length === 0) {
            imagesContainer.innerHTML = '<div class="info-value empty">暂无图片</div>';
            return;
        }

        imagesContainer.innerHTML = '';
        urls.forEach(url => {
            const imageItem = document.createElement('div');
            imageItem.className = 'image-item';
            imageItem.innerHTML = `<img src="${url}" alt="店铺图片" onclick="previewFile('${url}', '店铺图片', 'image')">`;
            imagesContainer.appendChild(imageItem);
        });
    } catch (e) {
        console.error('解析图片URL失败:', e);
        imagesContainer.innerHTML = '<div class="info-value empty">图片数据格式错误</div>';
    }
}

// 工具函数：格式化时间
function formatTime(timeString) {
    if (!timeString) return '';
    return timeString.substring(0, 5); // 提取 HH:mm 部分
}

// 工具函数：格式化日期时间
function formatDateTime(dateTimeString) {
    if (!dateTimeString) return '';
    try {
        const date = new Date(dateTimeString);
        return date.toLocaleString('zh-CN');
    } catch (e) {
        return dateTimeString;
    }
}

// 工具函数：获取默认头像
function getDefaultAvatar() {
    return '';
}

// 显示错误信息
function showErrorMessage(message) {
    const container = document.querySelector('.container');
    container.innerHTML = `
        <div style="text-align: center; padding: 50px;">
            <i class="bi bi-exclamation-triangle" style="font-size: 48px; color: #dc3545;"></i>
            <h3 style="margin: 20px 0; color: #dc3545;">加载失败</h3>
            <p>${message}</p>
            <button class="btn btn-primary" onclick="location.reload()" style="margin-top: 20px;">
                <i class="bi bi-arrow-clockwise"></i> 重新加载
            </button>
        </div>
    `;
}